package com.xuetang9.fujian.threaddemo.downloader;

import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @author: fujian
 * @description: 下载任务
 * @date: 2021/5/2 14:52
 * @version: V1.0
 * @package: com.xuetang9.fujian.threaddemo.downloader
 **/
public class DownloadTask implements Runnable{
    private String url;
    private int startPosition;
    private int partSize;
    private RandomAccessFile randomAccessFile;
    // 默认缓存大小
    private static final int MAX_BUFFER_SIZE = 1024 * 1024 * 2;
    /*
     * @Description:
     * @param: url 当前下载任务的目标地址
     * @param: startPosition 当前下载任务起始位置
     * @param: partSize 当前下载任务负责下载的总字节数
     * @param: partFile 当前下载任务负责下载的文件块
     * @author: fujian
     * @date 2021/5/2 15:03
    */
    public DownloadTask(String url, int startPosition, int partSize, RandomAccessFile partFile) {
        this.url = url;
        this.startPosition = startPosition;
        this.partSize = partSize;
        this.randomAccessFile = partFile;
    }

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName() + "开始下载任务");
        HttpURLConnection connection = null;
        InputStream inStream = null;
        try {
            connection = (HttpURLConnection) new URL(url).openConnection();
            connection.setRequestProperty("Range", "bytes=0-");
            connection.connect();   //连接到资源
            if (connection.getResponseCode() / 100 != 2){
                return; // 资源返回的状态码不在200-300之间
            }

            inStream = connection.getInputStream();
            int downloaded = 0;
            while (downloaded < partSize){
                byte[] buffer = null;
                if (partSize - downloaded > MAX_BUFFER_SIZE){
                    buffer = new byte[MAX_BUFFER_SIZE];
                }else {
                    buffer = new byte[partSize - downloaded];
                }
                int currentDownloaded = 0;
                int read = -1;
                while (currentDownloaded < buffer.length && (read = inStream.read()) != -1){
                    buffer[currentDownloaded++] = (byte) read;
                    downloaded++;
                }
                if (read == -1) break;
                // 将内容读取到缓存后，就把缓存写到硬盘上去
                randomAccessFile.write(buffer);

            }
            System.out.println(Thread.currentThread().getName() + "完成下载任务");

        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            connection.disconnect();
        }
    }
}
